// src/utils/api.js
import axios from "axios";
import { jwtDecode } from "jwt-decode";
import { BASE_URL } from "@/config";

const api = axios.create({
  // baseURL: "http://127.0.0.1:8000/",
  // baseURL: "http://10.63.161.12:8000/api",
  // baseURL: "https://ipss-bit.com/api",
  baseURL: BASE_URL,

  timeout: 10000,
});
// // 请求拦截器：自动加 token
// api.interceptors.request.use((config) => {
//   const token = localStorage.getItem("token");
//   if (token) {
//     config.headers.Authorization = `Bearer ${token}`;
//   }
//   return config;
// });

// 请求拦截器
api.interceptors.request.use((config) => {
  if (config.headers && config.headers.auth) {
    let token = localStorage.getItem("token");

    if (token) {
      try {
        const decoded = jwtDecode(token);
        const now = Date.now() / 1000;
        if (decoded.exp && decoded.exp < now) {
          console.warn("token 过期，已清理");
          localStorage.removeItem("token");
          token = null;
        }
      } catch (e) {
        console.error("token 无效，已清理", e);
        localStorage.removeItem("token");
        token = null;
      }
    }

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    } else {
      delete config.headers.Authorization;
    }

    delete config.headers.auth; // ⚠️ 删除自定义字段，避免发到后端
  }

  return config;
});

// 响应拦截器：处理 401
api.interceptors.response.use(
  (res) => res,
  (err) => {
    if (err.response && err.response.status === 401) {
      localStorage.removeItem("token");
      // window.location.href = "/login";
    }
    return Promise.reject(err);
  }
);
// 写法
// api.get("/user/info", {}{ headers: { auth: true } }) // 自动带 token

export default api;
